package edu.uiuc.ncsa.commons.util;

import edu.uiuc.ncsa.commons.NCSAKMLUtilityException;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;

/**
 * @author : Sachith Dhanushka (sachith.dhanushka@gmail.com)
 * @date : May 26, 2008 - 2:54:42 PM
 */
public class XSLUtil {


    // This method applies the xslFilename to inFilename and writes
    // the output to outFilename.
    public static void xslTransform(String inFilename, String outFilename, String xslFilename) throws NCSAKMLUtilityException {
        try {
            xslTransform(new FileInputStream(inFilename), new FileOutputStream(outFilename), xslFilename);
        } catch (FileNotFoundException e) {
            throw new NCSAKMLUtilityException(e);
        }

    }

    public static void xslTransform(InputStream inFileStream, OutputStream outFileStream, String xslFilename) throws NCSAKMLUtilityException {
        try {
            // Create transformer factory
            TransformerFactory factory = TransformerFactory.newInstance();

            // Use the factory to create a template containing the xsl file
            Templates template = factory.newTemplates(new StreamSource(
                    new FileInputStream(xslFilename)));

            // Use the template to create a transformer
            Transformer xformer = template.newTransformer();

            // Prepare the input and output files
            Source source = new StreamSource(inFileStream);
            Result result = new StreamResult(outFileStream);

            // Apply the xsl file to the source file and write the result to the output file
            xformer.transform(source, result);
        } catch (FileNotFoundException e) {
            throw new NCSAKMLUtilityException(e);
        } catch (TransformerConfigurationException e) {
            // An error occurred in the XSL file
            throw new NCSAKMLUtilityException(e);
        } catch (TransformerException e) {
            // An error occurred while applying the XSL file
            // Get location of error in input file
            SourceLocator locator = e.getLocator();
            int col = locator.getColumnNumber();
            int line = locator.getLineNumber();
            String publicId = locator.getPublicId();
            String systemId = locator.getSystemId();

            System.out.println("Error in line " + line + ", column " + col);

            throw new NCSAKMLUtilityException(e);
        }
    }


}
